package com.zerowidth.db.op;

import com.zerowidth.db.DBConn;
import com.zerowidth.db.DBHelper;
import com.zerowidth.db.base.SqlResult;
import com.zerowidth.db.bean.AppConfigBean;
import com.zerowidth.db.bean.SignAwardBean;
import com.zerowidth.db.bean.SignBean;
import com.zerowidth.db.utils.CollectionUtils;
import com.zerowidth.db.utils.IOUtils;
import com.zerowidth.db.utils.TimeUtils;
import com.zerowidth.moc.web.utils.MathUtil;
import com.zerowidth.moc.web.utils.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SignRecordDB {

    /**
     * 查询指定日期当天的签到用户数
     *
     * @param date
     * @return
     */
    public static int count(String date) {
        String sql = String.format("SELECT COUNT(*) FROM app_sign_record WHERE sign_date = '%s' ", date);

        return DBHelper.queryCount(sql);
    }


    /**
     * 查询签到返现成功奖励的用户记录
     *
     * @return
     */
    public static List<SignAwardBean> getSignAwardBeanList() {
        List<SignAwardBean> beanList = new ArrayList<>();


        String sql = String.format("SELECT * from app_sign_award WHERE enable = 1 ORDER BY id desc  limit 10");
        SqlResult sr = DBHelper.executeQueryEx(sql);

        try {
            ResultSet rs = sr.rs;
            while (rs.next()) {
                SignAwardBean bean = new SignAwardBean();
                beanList.add(bean);
                bean.nick_name = rs.getString("nick_name");
                bean.money = rs.getInt("money");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(sr);
        }

        return beanList;
    }

    public static List<SignAwardBean> getSignAwardBeanList(String date) {
        List<SignAwardBean> beanList = new ArrayList<>();


        String sql = String.format("SELECT * from app_sign_award WHERE enable = 1 AND date = '%s' ORDER BY id desc  limit 10", date);
        SqlResult sr = DBHelper.executeQueryEx(sql);

        try {
            ResultSet rs = sr.rs;
            while (rs.next()) {
                SignAwardBean bean = new SignAwardBean();
                beanList.add(bean);
                bean.nick_name = rs.getString("nick_name");
                bean.money = rs.getInt("money");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(sr);
        }

        return beanList;
    }

    public static int insertSignAward(String nickName, String date) {

        int money = 380;

        String sql = String.format("INSERT INTO app_sign_award(nick_name, money, enable, date) VALUES ('%s', %d, 1, '%s')",
                nickName, money, date);

        return DBHelper.executeInsert(sql);
    }

    public static int createSignRecord(String userId) {
        String currentDate = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_2);

        List<String> dateList = getSignForbidden();
        if (dateList.contains(currentDate)) {
            return -1;
        }

        String sql = String.format("INSERT INTO app_sign_record (user_id, sign_date) VALUES ('%s', '%s')", userId, currentDate);

        return DBHelper.executeInsert(sql);
    }

    public static List<String> getSignForbidden() {
        String sql = String.format("SELECT * FROM app_sign_forbidden_date");

        List<String> dateList = new ArrayList<>();
        ResultSet rs = null;
        try {
            rs = DBConn.getInst().getStmt().executeQuery(sql);
            if (rs != null) {
                while (rs.next()) {
                    String date = rs.getString("forbidden_date");
                    dateList.add(date);
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(rs);
        }

        return dateList;
    }

    public static SignBean getSignBean(String userId) {
        SignBean signBean = new SignBean();


        List<AppConfigBean> beanList = AppConfigDB.getAppConfigData("");

        //查询签到规则 数据
        for (int i = 0; i < CollectionUtils.size(beanList); i++) {
            if ("sign_open_flag".equals(beanList.get(i).config_key)) {
                AppConfigBean configBean = beanList.get(i);

                if (configBean != null) {
                    signBean.sign_open_flag = configBean.config_value.equals("1");
                }

                break;
            }
        }

        for (int i = 0; i < CollectionUtils.size(beanList); i++) {
            if ("sign_rules".equals(beanList.get(i).config_key)) {
                AppConfigBean configBean = beanList.get(i);

                if (configBean != null) {
                    signBean.sign_desc_list = configBean.config_value;
                }

                break;
            }
        }

        signBean.sign_award_list = new ArrayList<>();


        String dateToday = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_2);
        List<SignAwardBean> todayAwardList = getSignAwardBeanList(dateToday);
        if (CollectionUtils.size(todayAwardList) <= 1) {
            int count = MathUtil.randomFrom(2,3,4);
            for (int i = 0; i < count; i++) {
                String nickName = UserDB.randomPickName();

                if (StringUtils.length(nickName) > 8) {
                    nickName = StringUtils.subSequence(nickName, 0, 8);
                }

                nickName += "**";
                insertSignAward(nickName, dateToday);
            }
        }

        signBean.sign_award_list = getSignAwardBeanList();

        //查询签到记录 数据
        String sql = String.format("SELECT * from app_sign_record WHERE user_id = '%s' AND enable = 1", userId);

        SqlResult sr = DBHelper.executeQueryEx(sql);
        ResultSet rs = sr.rs;

        String todayDate = TimeUtils.convert(System.currentTimeMillis(), TimeUtils.TIME_FORMAT_YYYY_MM_DD_2);
        signBean.sign_date_list = new ArrayList<>();
        try {
            while (rs.next()) {
                String date = rs.getString("sign_date");
                signBean.sign_date_list.add(date);

                if (!signBean.has_sign_today && todayDate.equals(date)) {
                    signBean.has_sign_today = true;
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            IOUtils.close(sr);
            IOUtils.close(rs);
        }

        return signBean;
    }

}
